package com.itzou.controller;

import com.itzou.domain.ScheduledTask;
import com.itzou.domain.requestVo.StopTaskRequest;
import com.itzou.domain.requestVo.TaskRequest;
import com.itzou.domain.result.R;
import com.itzou.service.ScheduledTaskService;
import com.itzou.service.TaskSchedulerService;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 任务调度器控制器 - 改进版本
 * 把需要实现定时任务的模块引入到本项目的POM文件中，然后在本项目中调用即可
 *
 * @author Zou
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/task-scheduler")
public class TaskSchedulerController {

    private final TaskSchedulerService taskSchedulerService;
    private final ScheduledTaskService scheduledTaskService;

    /**
     * 启动定时任务
     * 示例（requestbody）：
     * {
     * "cronExpression": "0/15 * * * * ?", Cron表达式，如0/15 * * * * ? 表示每15秒执行一次
     * "serviceName": "taskTestServiceImpl", // Service实现类的类名（注意：需要小驼峰，如：jobServiceTestImpl）
     * "serviceMethod": "testPrint1" // Service实现类中的方法名称（注意：需要小驼峰且不能有小括号和参数，如：testPrint1）
     * }
     *
     * @param request 包含cron表达式、服务名称和方法名称的请求对象
     * @return 返回结果
     */
    @PostMapping("/start")
    public R<String> startTask(@Valid @RequestBody TaskRequest request) {
        boolean b = taskSchedulerService.startScheduledTask(request.getCronExpression(), request.getServiceName(), request.getServiceMethod());
        ScheduledTask scheduledTask = new ScheduledTask();
        scheduledTask.setServiceMethod(request.getServiceMethod());
        scheduledTask.setServiceName(request.getServiceName());
        scheduledTask.setCronExpression(request.getCronExpression());
        if (b) {
            ScheduledTask scheduledTask1 = scheduledTaskService.selectByCondition(request.getServiceName(), request.getServiceMethod());
            if (scheduledTask1 != null) {
                scheduledTaskService.updateStatus1(request.getServiceName(), request.getServiceMethod());
                return R.ok("定时任务启动成功：" + request.getServiceName() + "|" + request.getServiceMethod() + "|" + request.getCronExpression());
            }
            scheduledTask.setStatus(1);
            scheduledTaskService.insert(scheduledTask);
            return R.ok("定时任务启动成功：" + request.getServiceName() + "|" + request.getServiceMethod() + "|" + request.getCronExpression());
        }
        scheduledTask.setStatus(0);
        scheduledTaskService.insert(scheduledTask);
        return R.fail("定时任务启动失败！！！");
    }

    /**
     * 停止定时任务
     * 示例（body）：
     * {
     * "serviceName": "taskTestServiceImpl", // Service实现类的类名（注意：需要小驼峰，如：jobServiceTestImpl）
     * "serviceMethod": "testPrint1" // Service实现类中的方法名称（注意：需要小驼峰且不能有小括号和参数，如：testPrint1）
     * }
     *
     * @param request 包含服务名称和方法名称的请求对象
     * @return 返回结果
     */
    @PostMapping("/stop")
    public R<String> stopTask(@Valid @RequestBody StopTaskRequest request) {
        taskSchedulerService.stopScheduledTask(request.getServiceName(), request.getServiceMethod());
        scheduledTaskService.updateStatus0(request.getServiceName(), request.getServiceMethod());
        return R.ok("定时任务停止成功：" + request.getServiceName() + "|" + request.getServiceMethod());
    }

    /**
     * 根据ID查询定时任务
     * <p>
     * 示例：
     * {
     * "code": 200,
     * "msg": "success",
     * "data": {
     * "id": 1,
     * "serviceName": "taskTestServiceImpl",
     * "serviceMethod": "testPrint1",
     * "cronExpression": "0/15 * * * * ?",
     * "status": 1
     * }
     * }
     *
     * @param id 定时任务ID
     * @return 定时任务对象
     */
    @GetMapping("/findById")
    public R findById(Integer id) {
        return R.ok(scheduledTaskService.findById(id));
    }

    /**
     * 分页查询定时任务
     * <p>
     * 示例：
     * {
     * "code": 200,
     * "msg": "success",
     * "data": {
     * "records": [
     * {
     * "id": 1,
     * "serviceName": "taskTestServiceImpl",
     * "serviceMethod": "testPrint1",
     * "cronExpression": "0/15 * * * * ?",
     * "status": 1
     * }
     * ],
     * "total": 1,
     * "size": 10,
     * "current": 1,
     * "orders": [],
     * "optimizeCountSql": true,
     * "searchCount": true,
     * "maxLimit": null,
     * "countId": null,
     * "pages": 1
     * }
     * }
     *
     * @param pageNo   页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    @GetMapping("/findByPage")
    public R findByPage(@RequestParam(defaultValue = "1") Integer pageNo, @RequestParam(defaultValue = "10") Integer pageSize) {
        return R.ok(scheduledTaskService.findByPage(pageNo, pageSize));
    }
}
